package com.sixi.GeoTransfer;

import java.awt.Point;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;



public class KmlAnalyseSiChuan {

	public static void main(String[] args) {

		try {
			
			 //***************初始化文件流
			 File f = new File("./src/main/resources/sichuan_border.kml");
			 //**************输出文件流
			 FileOutputStream out = null;
			 out = new FileOutputStream(new File("./src/main/resources/sichuan_city_info.txt"));
				//***************建立dom解析模式
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				
				//***************初始化文件流
				Document doc = builder.parse(f);
				NodeList nodeList = doc.getElementsByTagName("coordinates");
				
				
				for(int i = 0 ; i < nodeList.getLength() ; i ++) {
					                                            //coordinates/LinearRing/outerBoundaryIs/Polygon/MultiGeometry/Placemark
					NodeList placemarkChildNodes = nodeList.item(i).getParentNode().getParentNode().getParentNode().getParentNode().getParentNode().getChildNodes();
					String name = "";
					for(int j = 0 ;j < placemarkChildNodes.getLength() ; j ++) {
						if(placemarkChildNodes.item(j).getNodeName().equals("name")) {
							name = placemarkChildNodes.item(j).getTextContent().trim();
						}
					}
					String[] points = nodeList.item(i).getTextContent().split("\n");
					String outply = "";
					for(String pt : points) {
						if(pt.length() >= 2) {
							outply += pt.trim().substring(0, pt.length()-2) +  ";";
						}
					}
					
					String outPutStr = name + "\t" + outply.substring(0, outply.length()-1) + "\r\n";
					out.write(outPutStr.getBytes("utf-8"));
					
				}
			 
				out.close();
				
				
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

}
